
const fs = require('fs');
const path = require('path');

/**
 * 路由文件命令规则
 * 1. 一个路由一个文件夹，文件夹名称会作为路由名称，文件夹下需要包含index.ts入口文件，不包含的不会自动导入理由
 * 2. target 路由配置文件位置，绝对路径
 * 3. views  页面存放路径，绝对路径
 * @returns Plugin
 */
const VitePluginAutoRouter = (opts) => {
    return {
        name: 'vite-plugin-auto-router',
        load(id) {
            const target = opts.target.replace(/\\/g, '/');
            const views = opts.views.replace(/\\/g, '/');
            if (id == target) {
                const imps = [];
                const loopDir = (root) => {
                    fs.readdirSync(root).forEach((name) => {
                        const dir = path.join(root, name).replace(/\\/g, '/');
                        const stat = fs.statSync(dir);
                        if (stat.isDirectory()) {
                            loopDir(dir);
                            return;
                        }
                        if (name == 'index.ts' || name == 'index.tsx') {
                            const path = dir.replace(views, '').replace(`/${name}`, '');
                            const imp = `router.addRoute({path: '${path}', name: '${path}',component: () => import('${dir}')});`;
                            imps.push(imp);


                        }
                    });
                }
                loopDir(views);
                const origin = fs.readFileSync(id);
                const content = `${origin}\n${imps.join('\n')}`;
                return content;

            }
        },
    }
}

module.exports = VitePluginAutoRouter;